<template>
  <div class="common-table">
    <!-- 页面标题和操作按钮 -->
    <div v-if="config.showHeader" class="table-header">
      <div class="table-title">
        <h2>{{ config.title }}</h2>
        <p v-if="config.description">{{ config.description }}</p>
      </div>
      <div class="table-actions">
        <slot name="header-actions">
          <el-button
              v-if="config.showAddButton"
              type="primary"
              @click="handleAdd"
          >
            <el-icon>
              <Plus/>
            </el-icon>
            {{ config.addButtonText || '新增' }}
          </el-button>
          
          <!-- 自定义头部操作按钮 -->
          <el-button
              v-for="(action, index) in config.customHeaderActions"
              :key="index"
              :type="action.type || 'default'"
              @click="action.handler"
          >
            <el-icon v-if="action.icon">
              <component :is="action.icon" />
            </el-icon>
            {{ action.text }}
          </el-button>
        </slot>
      </div>
    </div>

    <!-- 高级搜索 -->
    <div v-if="config.showSearch" class="search-form">
      <AdvancedSearch
          :fields="config.searchFields || []"
          v-model="searchConditions"
          @search="handleSearch"
          @reset="handleSearchReset"
      >
        <template #extraButtons>
          <div>
            <slot name="extraButtons"/>
            <!-- 列设置 -->
            <ColumnSettings
                :columns="props.columns"
                @settings-change="handleColumnSettingsChange"
            />
          </div>
        </template>

      </AdvancedSearch>

    </div>

    <!-- 表格 -->
    <div class="table-container">
      <el-table
          ref="tableRef"
          v-loading="loading"
          :data="tableData"
          :stripe="config.stripe !== false"
          :border="config.border !== false"
          style="width: 100%;height: 100%;"
          v-bind="config.tableProps"
          @selection-change="handleSelectionChange"
          @sort-change="handleSortChange"
      >
        <!-- 多选列 -->
        <el-table-column
            v-if="config.showSelection"
            type="selection"
            width="55"
            align="center"
        />

        <!-- 序号列 -->
        <el-table-column
            v-if="config.showIndex"
            type="index"
            label="序号"
            width="60"
            align="center"
            :index="getIndex"
        />

        <!-- 动态列 -->
        <el-table-column
            v-for="column in visibleColumns"
            :key="column.prop"
            :prop="column.prop"
            :label="column.label"
            :width="column.width"
            :min-width="column.minWidth"
            :fixed="column.fixed"
            :align="column.align || 'left'"
            :sortable="column.sortable"
            :show-overflow-tooltip="column.showOverflowTooltip !== false"
        >
          <template #default="{ row, column: col, $index }">
            <slot
                :name="column.prop"
                :row="row"
                :column="col"
                :index="$index"
                :value="row[column.prop]"
            >
              <!-- 默认渲染 -->
              <span v-if="!column.render && !column.formatter">
                  {{ formatCellValue(row, column) }}
                </span>

              <!-- 自定义渲染函数 -->
              <component
                  v-else-if="column.render"
                  :is="column.render"
                  :row="row"
                  :column="col"
                  :index="$index"
                  :value="row[column.prop]"
              />

              <!-- 格式化函数 -->
              <span v-else-if="column.formatter">
                  {{ column.formatter(row, col, row[column.prop], $index) }}
                </span>
            </slot>
          </template>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column
            v-if="config.showActions"
            label="操作"
            :width="config.actionWidth || 200"
            :fixed="config.actionFixed || 'right'"
            align="center"
        >
          <template #default="{ row, $index }">
            <slot name="actions" :row="row" :index="$index">
              <el-button
                  v-if="config.showEditButton"
                  type="primary"
                  size="small"
                  @click="handleEdit(row, $index)"
              >
                编辑
              </el-button>
              <el-button
                  v-if="config.showDeleteButton"
                  type="danger"
                  size="small"
                  @click="handleDelete(row, $index)"
              >
                删除
              </el-button>
            </slot>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div v-if="config.showPagination !== false" class="pagination">
        <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.size"
            :page-sizes="config.pageSizes || [10, 20, 50, 100]"
            :total="pagination.total"
            :layout="config.paginationLayout || 'total, sizes, prev, pager, next, jumper'"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {computed, onMounted, reactive, ref, watch} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Plus, Download} from '@element-plus/icons-vue'
import {useRoute} from 'vue-router'
import {useUserStore} from '@/stores/user'
import AdvancedSearch from '@/components/base/AdvancedSearch/index.vue'
import ColumnSettings from './ColumnSettings.vue'
import type {SearchCondition} from '@/types/search'
import type {CommonTableEmits, CommonTableProps, TableColumn} from './types'
import type {ColumnSetting} from './types'
import {ColumnSettingsManager} from './index'

const props = withDefaults(defineProps<CommonTableProps>(), {
  immediate: true
})

const emit = defineEmits<CommonTableEmits>()

// 路由和用户信息
const route = useRoute()
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const tableData = ref<any[]>([])
const tableRef = ref()
const searchConditions = ref<SearchCondition[]>([])
const selectedRows = ref<any[]>([])
const columnSettings = ref<ColumnSetting[]>([])

// 分页信息
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 排序信息
const sortInfo = ref<any>({})

// 计算属性
const visibleColumns = computed(() => {
  if (columnSettings.value.length === 0) {
    return props.columns.filter(column => !column.hidden)
  }
  
  // 根据列设置过滤和排序
  const settingsMap = new Map(columnSettings.value.map(s => [s.prop, s]))
  return props.columns
    .filter(column => {
      const setting = settingsMap.get(column.prop)
      return setting ? setting.visible : !column.hidden
    })
    .sort((a, b) => {
      const settingA = settingsMap.get(a.prop)
      const settingB = settingsMap.get(b.prop)
      const orderA = settingA ? settingA.order : 999
      const orderB = settingB ? settingB.order : 999
      return orderA - orderB
    })
})

// 方法
const getIndex = (index: number) => {
  return (pagination.current - 1) * pagination.size + index + 1
}

const formatCellValue = (row: any, column: TableColumn) => {
  const value = row[column.prop]
  if (value === null || value === undefined) {
    return '-'
  }
  return value
}

// 加载数据
const loadData = async () => {
  try {
    loading.value = true

    const params = {
      pageNum: pagination.current,
      pageSize: pagination.size,
      query: {},
      advancedQuery: {
        conditions: searchConditions.value.map(condition => ({
          field: condition.field,
          operator: condition.operator,
          value: condition.value,
          value2: condition.value2
        })),
        logic: searchLogic.value
      },
      ...sortInfo.value
    }

    const result = await props.api.listApi(params)

    tableData.value = result.list || result.records || []
    pagination.total = result.total || 0

    emit('refresh')
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索相关
const searchLogic = ref<'AND' | 'OR'>('AND')

  const handleSearch = (searchQuery: any) => {
  if (searchQuery.conditions) {
    // 新的数据结构，包含logic字段
    searchConditions.value = searchQuery.conditions
    searchLogic.value = searchQuery.logic || 'AND'
  } else {
    // 兼容旧的数据结构
    searchConditions.value = searchQuery
    searchLogic.value = 'AND'
  }
  pagination.current = 1
  loadData()
}

// 重置搜索
const handleSearchReset = () => {
  searchConditions.value = []
  searchLogic.value = 'AND'
  pagination.current = 1
  loadData()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  loadData()
}

const handleCurrentChange = (current: number) => {
  pagination.current = current
  loadData()
}

// 排序处理
const handleSortChange = (sort: any) => {
  if (sort.prop) {
    sortInfo.value = {
      orderBy: sort.prop,
      orderMode: sort.order === 'ascending' ? 'ASC' : 'DESC'
    }
  } else {
    sortInfo.value = {}
  }

  loadData()
  emit('sort-change', sort)
}

// 选择处理
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
  emit('selection-change', selection)
}

// 操作处理
const handleAdd = () => {
  emit('add')
}

const handleEdit = (row: any, index: number) => {
  emit('edit', row, index)
}

const handleDelete = async (row: any, index: number) => {
  if (!props.api.deleteApi) {
    emit('delete', row, index)
    return
  }

  try {
    await ElMessageBox.confirm(
        '确定要删除这条记录吗？',
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    await props.api.deleteApi(row.id)
    ElMessage.success('删除成功')
    loadData()
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 列设置处理
const handleColumnSettingsChange = (settings: ColumnSetting[]) => {
  columnSettings.value = settings
}

// 初始化列设置
const initColumnSettings = () => {
  const userId = userStore.userInfo?.userId || 'anonymous'
  const pagePath = route.path
  const savedSettings = ColumnSettingsManager.loadColumnSettings(userId, pagePath)
  if (savedSettings.length > 0) {
    columnSettings.value = savedSettings
  }
}

// 暴露的方法
const refresh = () => {
  loadData()
}

const getSelectedRows = () => {
  return selectedRows.value
}

const clearSelection = () => {
  tableRef.value?.clearSelection()
}

// 监听配置变化
watch(() => props.config.tableId, () => {
  initColumnSettings()
  if (props.immediate) {
    loadData()
  }
})



// 暴露方法给父组件
defineExpose({
  refresh,
  loadData,
  getSelectedRows,
  clearSelection,
  tableRef
})

// 初始化
onMounted(() => {
  initColumnSettings()
  if (props.immediate) {
    loadData()
  }
})
</script>

<style scoped>
.common-table {
  padding: 0;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  margin-bottom: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  flex-shrink: 0;
}

.table-title h2 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 24px;
}

.table-title p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.search-form {
  flex-shrink: 0;
}

.table-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100%;
}

:deep(.el-card__body) {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

:deep(.el-table) {
  flex: 1;
}

.pagination {
  margin-top: 20px;
  text-align: right;
  flex-shrink: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .table-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .table-actions {
    margin-top: 16px;
    width: 100%;
  }
}
</style>